package com.yinhaochuan.xmlparse;

import java.util.Iterator;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.yinhaochuan.data.Doc;


public class DomXmlParser {
	Vector<Doc> docVector;
	
	private Vector<Doc> readXMLFile(String file)throws Exception {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = dbf.newDocumentBuilder();
		Document doc = builder.parse(file);
		
		Element root = doc.getDocumentElement();
		NodeList Docs = root.getElementsByTagName("DOC");
        docVector = new Vector<Doc>();
        for (int i = 0; i < Docs.getLength(); i++) {
          
            Element ss = (Element) Docs.item(i);
            Doc ddoc = new Doc();
            
            NodeList docNos = ss.getElementsByTagName("DOCNO");
            Element e = (Element) docNos.item(0);
            Node t = e.getFirstChild();
            ddoc.setDocNO(t.getNodeValue());
            
            NodeList Langs = ss.getElementsByTagName("LANG");
            e = (Element) Langs.item(0);
            t = e.getFirstChild();
            ddoc.setLang(t.getNodeValue());
            
            NodeList Headlines = ss.getElementsByTagName("HEADLINE");
            e = (Element) Headlines.item(0);
            t = e.getFirstChild();
            ddoc.setHeadline(t.getNodeValue());
            
            NodeList Dates = ss.getElementsByTagName("DATE");
            e = (Element) Dates.item(0);
            t = e.getFirstChild();
            ddoc.setDate(t.getNodeValue());
            
            NodeList Texts = ss.getElementsByTagName("TEXT");
            e = (Element)Texts.item(0);
            t = e.getFirstChild();
            ddoc.setText(t.getNodeValue());
            
            
            
            docVector.add(ddoc);
        }
		return docVector;
	}
	
	public static void main(String[] args) {
		String string = "data/corpus/ude2000";
		DomXmlParser t = new DomXmlParser();
		System.out.println("START");
		
		Vector<Doc> vector;
		try {
			vector = t.readXMLFile(string);
			Iterator<Doc> iterator = vector.iterator();
			while (iterator.hasNext()) {
				Doc doc = (Doc) iterator.next();
				System.out.println(doc.getHeadline());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
